package com.fqy.thread02.procon01;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * User: fqy
 * Date: 2021/9/1
 * Time: 18:48
 * Describe: 使用LOCK解决高并发问题（0 1切换，数据出错）
 */
public class AirConditionWithLock {

    private Integer number = 0;

    Lock lock = new ReentrantLock();

    Condition condition = lock.newCondition();

    public void increament() throws InterruptedException {
        lock.lock();
        try {
            //1 判断
            while (number != 0){
                condition.await();
            }
            //2 干活
            System.out.println(Thread.currentThread().getName()+"\t"+(++number));
            //3 通知
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    public void decreament() throws InterruptedException {
        lock.lock();
        try {
            //1 判断
            while (number != 1){
                condition.await();
            }
            //2 干活
            System.out.println(Thread.currentThread().getName()+"\t"+(--number));
            //3 通知
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
}
